package org.itboys.shop.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.record.aggregates.PageSettingsBlock;
import org.itboys.admin.entity.BusinessCenter;
import org.itboys.admin.service.BusinessCenterService;
import org.itboys.baseobject.entity.KVConfig;
import org.itboys.basetemplate.entity.Favorite;
import org.itboys.basetemplate.service.FavoriteService;
import org.itboys.commons.CommonConstants.NUM;
import org.itboys.commons.CommonConstants.StaticParam;
import org.itboys.commons.utils.tools.ImagePathUtils;
import org.itboys.commons.utils.tools.ResponseManager;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.product.entity.Product;
import org.itboys.product.entity.ProductCategory;
import org.itboys.product.service.ProductCategoryService;
import org.itboys.product.service.ProductService;
import org.itboys.seller.service.SellerService;
import org.itboys.shop.dto.pro.WXProListDto;
import org.itboys.shop.dto.pro.WXShopDetailDto;
import org.itboys.shop.dto.pro.WXShopListDto;
import org.itboys.shop.entity.ShopSeller;
import org.itboys.shop.service.ShopSellerService;
import org.itboys.shop.service.Manager.WXProManager;
import org.itboys.shop.service.Manager.WXShopManager;
import org.itboys.shop.tools.WXSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 商品
 * @author 
 *
 */
@RestController
@RequestMapping("/wx/shop")
public class WXShopController extends BaseController{
	@Autowired
	private ShopSellerService shopService;
	@Autowired
	private WXShopManager shopManager;
	@Autowired
	private BusinessCenterService businessCenterService;
	@Autowired
	private FavoriteService favoriteService;
	/**
	 * 
	 * @param type shopType 2-民宿3-基地4-景点5-农家乐
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/shopList")
	public ModelAndView shopList(
			@Param("orderBy")Integer orderBy,//1 人气 2销量 3 附近 4 价格 升序 5价格降序
			@Param("type")int type,
			@Param("pageNo")Integer pageNo,
			@Param("pageSize")Integer pageSize,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			Member member=WXSession.getMember(request);
			Map<String, Object> param = new HashMap<>();
			if (null==orderBy) {
				orderBy=1;
			}
			param.put("pageNo", null==pageNo?1:pageNo);
			param.put("pageSize", null==pageSize?100:pageSize);
            param.put("centerId", member.getCenterId());
            param.put("shopType", type); //民宿
			List<ShopSeller>sellers=Lists.newArrayList();
			switch (orderBy) {
			case 1:
				param.put("orderByKey", "-hitRate");
				sellers=shopService.listWithPaging(param);
				break;
			case 2:
				param.put("orderByKey", "-soldCount");
				sellers=shopService.listWithPaging(param);
				break;
			case 3:
				sellers=shopService.listWithPaging(param);
				//param.put("orderByKey", "-ct");
				break;
			case 4:
				sellers=shopService.listWithPaging(param);
				//param.put("orderByKey", "price");
				break;
			case 5:
				sellers=shopService.listWithPaging(param);
				//param.put("orderByKey", "-price");
				break;
			default:
				break;
			}
		
			List<WXShopListDto>result=sellers.stream().map(s->{
				WXShopListDto dto=new WXShopListDto();
				dto.setShopId(s.getId());
				dto.setImage(ImagePathUtils.add(StaticParam.imagePath, s.getMainImg()));
				dto.setName(s.getShopName());
				dto.setPrice(NUM.DF_00.format(shopService.getMinPrice(s.getId())/100));
				dto.setAdvantageDesc(s.getAdvantageDesc());
				return dto;
			}).collect(Collectors.toList());
			model.addAttribute("shops", result);
			model.addAttribute("orderBy", orderBy);
		} catch (Exception e) {
			logger.error("",e);
		}
		switch (type) {
		case 2:
			return new ModelAndView("/shop/ShopList_ms");
		case 4:
			return new ModelAndView("/shop/ShopList_jd");
		case 5:
			return new ModelAndView("/shop/ShopList_njl");
		default:
			return null;
		}
	}
	@RequestMapping("/shopDetail")
	public ModelAndView shopDetail(@RequestParam Long shopId,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		ShopSeller shop=shopService.getById(shopId);
		BusinessCenter center = businessCenterService.getById(shop.getCenterId());
		model.addAttribute("weixinId", center.getWeixinId());
		try {
			WXShopDetailDto dto=shopManager.getWXShopDetailDto(shop);
			shopService.update(shopId, "hitRate", null==shop.getHitRate()?1:shop.getHitRate()+1);
			model.addAttribute("shop", dto);
		} catch (Exception e) {
			logger.error("",e);
		}
		
		Member member = (Member)request.getSession().getAttribute("user");
		Long memberId = member.getId();
		Map<String,Object> param = new HashMap<>();
		param.put("memberId", memberId);
		param.put("objId",shopId);
		param.put("type", shop.getShopType());
		Favorite favorite = favoriteService.getFirst(param);
		
		//商品是否被收藏	0：已收藏	1：取消收藏
		Integer isCollect = 1; 
		if(favorite!=null){
			 isCollect = favorite.getIsDeleted();
		}
		model.addAttribute("isCollect", isCollect);
		
		model.addAttribute("type", shop.getShopType());
		switch (Long.valueOf(shop.getShopType()).intValue()) {
		case 2:
			return new ModelAndView("/shop/ShopDetail_ms");
		case 4:
			return new ModelAndView("/shop/ShopDetail_jd");
		case 5:
			return new ModelAndView("/shop/ShopDetail_njl");
		default:
			return null;
		}
	}
	@RequestMapping("/recShops")
	public void recShops(@Param("type")int type,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			Member member=WXSession.getMember(request);
			Map<String, Object> param = new HashMap<>();
			param.put("pageNo", 1);
			param.put("pageSize", 4);
            param.put("centerId",member.getCenterId());
            param.put("shopType", type); //民宿
            param.put("orderByKey", "-ct");
			List<ShopSeller>sellers=shopService.listWithPaging(param);
			List<WXShopListDto>result=sellers.stream().map(s->{
				WXShopListDto dto=new WXShopListDto();
				dto.setShopId(s.getId());
				dto.setImage(ImagePathUtils.add(StaticParam.imagePath, s.getMainImg()));
				dto.setName(s.getShopName());
				dto.setPrice(NUM.DF_00.format(shopService.getMinPrice(s.getId())/100));
				dto.setAdvantageDesc(s.getAdvantageDesc());
				return dto;
			}).collect(Collectors.toList());
			ResponseManager.normalResult(result, response);
		} catch (Exception e) {
			logger.error("",e);
		}
	}
	@RequestMapping("/nearShops")
	public void nearShops(@Param("shopId")Long shopId,@Param("type")int type,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			List<ShopSeller>sellers=shopService.getNear(shopId, type);
			List<WXShopListDto>result=sellers.stream().map(s->{
				WXShopListDto dto=new WXShopListDto();
				dto.setShopId(s.getId());
				dto.setImage(ImagePathUtils.add(StaticParam.imagePath, s.getMainImg()));
				dto.setName(s.getShopName());
				dto.setPrice(NUM.DF_00.format(shopService.getMinPrice(s.getId())/100));
				dto.setAdvantageDesc(s.getAdvantageDesc());
				return dto;
			}).collect(Collectors.toList());
			ResponseManager.normalResult(result, response);
		} catch (Exception e) {
			logger.error("",e);
		}
	}
}
